<template>
	<div>
		<div class="CitySearch">
			<input placeholder="请输入城市或拼音" class="search-input" v-model='keyword'/>
		</div>
		<div class="search-content" ref='go' v-show='keyword'>
			<ul>
				<li v-for='item in list' class="border-bottom search-city" :key='item.id' @click='handleCityClick(item.name)'>
					{{item.name}}
				</li>
				<li class="border-bottom search-city" v-show='noData'>没有找到匹配数据</li>
			</ul>
		</div>
	</div>
</template>

<script>
import { mapMutations } from 'vuex'	
import BScroll from 'better-scroll'
export default {	
	name: 'CitySearch',
	props: {
		cities: Object
	},
	data () {
		return{
			keyword: '',
			timer: null,
			list: []
		}
	},
	mounted () {
		this.scroll = new BScroll(this.$refs.go)
	},
	computed: {
		noData () {
			return !this.list.length
		}
	},
	watch: {
		keyword () {
			if (this.timer) {
				clearTimeout(this.timer)
			}
			if (!this.keyword) {
				this.list = []
				return
			}
			this.timer = setTimeout( () => {
				const result = []
				for (let i in this.cities) {
						this.cities[i].forEach((value) => {
							if (value.name.indexOf(this.keyword) > -1 || value.spell.indexOf(this.keyword) > -1) {
								result.push(value)
							}
						})
				}
					this.list = result
			}, 100)
		}
	},
	methods: {
		handleCityClick (city) {
			// this.$store.commit('changeCity', city)
			this.changeCity(city)
			this.$router.push('/')
		},
		...mapMutations(['changeCity'])
	}

}	
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
	.CitySearch
		height: .72rem
		padding: 0 .1rem
		background: $bgColor
		text-align: center
		.search-input
			width: 95%
			height: .62rem
			line-height: .62rem
			padding: 0 .1rem
			color: #666
			border-radius: .06rem
			text-align: center
	.search-content
		position: absolute
		top: 1.58rem
		right: 0
		left: 0
		bottom: 0
		background: #eee
		z-index: 1
		overflow: hidden
		.search-city
			line-height: .68rem
			padding-left: .2rem
			background: #fff
</style>